import { useEffect } from "react";
import { Space, Pagination, Divider, Table, message } from "antd";
import { Button, ButtonGroup, Card as SemiCard } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useRelatedOrganization } from "@share-code/public";

const { Column } = Table;

const AllNotNormalAffiliateOrganizations = () => {
    const { remoteData, UTCTimeToLocal, windowInnerHeight, graphqlFetch } = useModel("global");
    const { baseInfo } = useModel("person.info");
    const { organizationUuid, organizationInfo } = useModel("organization.info");

    const { loadAllRelatedOrganizationsNotNormalWithPage, updateRelatedOrganizationStatus } =
        useRelatedOrganization(graphqlFetch);

    const state = useReactive({
        loading: false,
        noNormalAffiliates: [],
        totalCount: 0,
        pageSize: 20,
        page: 1,
    });

    const loadNoNormalAffiliates = async () => {
        state.loading = true;
        let res = await loadAllRelatedOrganizationsNotNormalWithPage({
            first: state.pageSize,
            offset: (state.page - 1) * state.pageSize,
        });
        state.noNormalAffiliates = res?.data || [];
        state.totalCount = res?.totalCount || 0;
        state.loading = false;
    };

    useEffect(() => {
        loadNoNormalAffiliates();
    }, [state.page]);

    const reApply = async (record) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/api/public_api_service",
            organizationUuid: record.oaUuid,
            params: {
                apiPath: "/organization/relatedApply",
                data: {
                    oaUuid: organizationUuid,
                    oaName: organizationInfo.fullName,
                    oaCaus: "重新申请",
                    oaApid: baseInfo.uuid,
                    oaApna: baseInfo.realName,
                },
            },
        });
        if (res) {
            if (res?.oaStat === "待审核") {
                message.warning((res?.oaCaus ? res.oaCaus + ", " : "") + "申请待审核中");
            }
            if (res?.oaStat === "正常") {
                message.success("申请关联的组织已确认");
                let res = await updateRelatedOrganizationStatus({
                    oaUuid: record.oaUuid,
                    oaStat: "正常",
                    oaAust: true,
                });
                if (res) {
                    message.success("转正常组织关联操作成功");
                    loadNoNormalAffiliates();
                }
            }
        }
    };

    const handleToNormal = async (record, index) => {
        let res = await updateRelatedOrganizationStatus({
            oaUuid: record.oaUuid,
            oaStat: "正常",
            oaAust: true,
        });
        if (res) {
            message.success("转正常组织关联操作成功");
            loadNoNormalAffiliates();
        }
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48 - 60;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 15 }}>非正常关系组织列表</span>}
            headerStyle={{ padding: "7px 12px" }}
            headerExtraContent={
                <ButtonGroup>
                    <Button icon={<IconRefresh />} onClick={() => loadNoNormalAffiliates()}>
                        刷新
                    </Button>
                </ButtonGroup>
            }
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight }}
            footerStyle={{ padding: 0 }}
            footerLine={true}
            footer={
                <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                    <div></div>
                    <Pagination
                        total={state.totalCount}
                        showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                        pageSize={state.pageSize}
                        current={state.page}
                        showSizeChanger={false}
                        onChange={(page, pageSize) => (state.page = page)}
                    />
                </div>
            }
        >
            <Table
                loading={state.loading}
                bordered
                size="small"
                pagination={false}
                dataSource={state.noNormalAffiliates}
                rowKey={"oaUuid"}
                scroll={{ y: cardBodyHeight - 40 }}
            >
                <Column
                    title="序号"
                    dataIndex="orderNo"
                    align="center"
                    width={80}
                    render={(_, record, index) => (state.page - 1) * state.pageSize + index + 1}
                />
                <Column title="组织名称" dataIndex="oaName" align="left" />
                <Column title="组织关系" dataIndex="oaRela" align="center" />
                <Column title="关联原由" dataIndex="oaCaus" align="center" />
                <Column
                    title="申请时间"
                    align="center"
                    width={160}
                    render={(_, record) => UTCTimeToLocal(record.oaApti)}
                />
                <Column
                    title="是否发起方"
                    align="center"
                    width={120}
                    render={(_, record) => (record.oaIsme ? "是" : "否")}
                />
                <Column
                    title="审核状态"
                    align="center"
                    width={100}
                    render={(_, record) =>
                        record.oaAust ? <span className="green">已核准</span> : <span className="red">待核准</span>
                    }
                />
                <Column title="关系状态" dataIndex="oaStat" align="center" width={100} />
                <Column
                    title="操作"
                    key="operations"
                    align="center"
                    width={100}
                    render={(_, record) => {
                        return (
                            <Space split={<Divider type="vertical" />} size={0}>
                                {record.oaIsme && <a onClick={() => reApply(record)}>重新申请</a>}
                                {!record.oaIsme && (record.oaStat === "已拒绝" || record.oaStat === "已驳回") && (
                                    <a onClick={() => handleToNormal(record)}>转正常</a>
                                )}
                                {record.oaStat === "已解除" && <a onClick={() => handleToNormal(record)}>转正常</a>}
                            </Space>
                        );
                    }}
                />
            </Table>
        </SemiCard>
    );
};

export default AllNotNormalAffiliateOrganizations;
